package com.iwe3.protal.aspects;

import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONUtil;
import com.iwe3.protal.Enum.SystemEnum;
import com.iwe3.protal.common.R;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class URLIdeamAspect {

    private final RedisTemplate redisTemplate;

    public URLIdeamAspect(@Qualifier("redisTemplate") RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Around("@annotation(uia)")
    public Object around(ProceedingJoinPoint pjp, URLIdemAnnotation uia) throws Throwable{

        //获得目标方法的参数
        Object[] args = pjp.getArgs();
        String clsName = pjp.getTarget().getClass().getName();
        String methName = pjp.getSignature().getName();
        String encode = Base64.encode(clsName + methName + JSONUtil.toJsonStr(args));
        /*一锁 ，二判，三更新*/
        //二判
        if(redisTemplate.hasKey(encode)){
            return R.fail(SystemEnum.RESUBMIT);
        }
        //三更新
        Object res = pjp.proceed(args);

        //一锁
        redisTemplate.opsForValue()
                .setIfAbsent(encode,"",uia.timeout(),uia.timeUnit());

        return res;
    }
}
